#!/bin/bash
PYTHON_DIR=$3
TESTFILE=$1
TIMEOUT=$2
JUDGE_TYPE=$4
OUTPUT_FILE="$PYTHON_DIR/__list_output.txt"
PROGRAM_OUTPUT_FILE="$PYTHON_DIR/__program_output_file.txt"
CURRENT_PATH=$( cd "$( dirname "$0" )" && pwd )
RUNFILE="$PYTHON_DIR/__list_output/$TESTFILE.py"
TEST_INPUT="$PYTHON_DIR/test_data/test_input.txt"
TEST_TARGET="$PYTHON_DIR/test_data/test_target.txt"
TEST_JUDGE_SCRIPT="$PYTHON_DIR/test_data/test_judge.py"

mkdir "$PYTHON_DIR/__list_output" > /dev/null 2> /dev/null
chgrp testovac "$PYTHON_DIR/__list_output" > /dev/null 2> /dev/null
chmod g+rwx "$PYTHON_DIR/__list_output" > /dev/null 2> /dev/null
chgrp testovac "$PYTHON_DIR/." > /dev/null 2> /dev/null
chmod g+r "$PYTHON_DIR/." > /dev/null 2> /dev/null

echo "<pre>" > $OUTPUT_FILE

echo "Stage 1 / 1: running test ..." >> $OUTPUT_FILE
echo "----- Running user code from file $TESTFILE.py<br />" >> $OUTPUT_FILE
cp -r $PYTHON_DIR/* $PYTHON_DIR/__list_output > /dev/null 2> /dev/null
rm -f "$PYTHON_DIR/__list_output/__list_output.txt" > /dev/null 2> /dev/null
rm -rf "$PYTHON_DIR/__list_output/test_data" > /dev/null 2> /dev/null
rm -f $PYTHON_DIR/__list_encrypt_phrase.txt 2> /dev/null
chgrp testovac "$PYTHON_DIR/_list_output/*" > /dev/null 2> /dev/null
cd "$PYTHON_DIR/__list_output/" > /dev/null 2> /dev/null
cat $TEST_INPUT | sudo -u testovac "$CURRENT_PATH/exec_pythonIO_test" $TESTFILE $TIMEOUT $CURRENT_PATH >> $PROGRAM_OUTPUT_FILE 2>> $OUTPUT_FILE
STATUS=$?
if [[ $STATUS == 0 ]] ; then
	if [[ "$JUDGE_TYPE" == "judge-type-diff" ]] ; then
		diff $TEST_TARGET $PROGRAM_OUTPUT_FILE > /dev/null 2> /dev/null
		JUDGE_STATUS=$?
		if [[ $JUDGE_STATUS == 0 ]] ; then
			echo "----- Result matches expected target!" >> $OUTPUT_FILE
			echo "</pre>" >> $OUTPUT_FILE
			exit 0
		else
			echo "----- Result is else that expected target!" >> $OUTPUT_FILE
			echo "</pre>" >> $OUTPUT_FILE
			exit 1
		fi
	fi
	if [[ "$JUDGE_TYPE" == "judge-type-script" ]] ; then
		chgrp testovac $TEST_JUDGE_SCRIPT > /dev/null 2> /dev/null
		cat $PROGRAM_OUTPUT_FILE | sudo -u testovac "$CURRENT_PATH/exec_pythonIO_judge" $TEST_JUDGE_SCRIPT $TEST_INPUT $CURRENT_PATH >> $OUTPUT_FILE 2>> $OUTPUT_FILE
		JUDGE_STATUS=$?
		if [[ $JUDGE_STATUS == 0 ]] ; then
			echo "----- Result pass judge script successfully." >> $OUTPUT_FILE
			echo "</pre>" >> $OUTPUT_FILE
			exit 0
		else
			echo "----- Result failed to pass judge script." >> $OUTPUT_FILE
			echo "</pre>" >> $OUTPUT_FILE
			exit 1
		fi
	fi
	echo "----- NO JUDGE SPECIFIED!" >> $OUTPUT_FILE
	echo "</pre>" >> $OUTPUT_FILE
	exit 10
else
	echo "----- RUN TIME ERROR!" >> $OUTPUT_FILE
	echo "</pre>" >> $OUTPUT_FILE
	exit 100
fi
